package com.bcsp.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class Test1 {

    public static void main(String[] args) throws Exception {
        //读取a.xml的信息
        //获取程序运行的目录
        String path = Test1.class.getClassLoader().getResource("").getPath();
        System.out.println(path);
        //解析器工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析xml文档
        Document doc = db.parse(path + "a.xml");
        //获取根节点
        Node root = doc.getFirstChild();
        //获取根节点的字节点列表
        NodeList nodeList = root.getChildNodes();
        for(int i = 0; i < nodeList.getLength(); i++){
            //如果是文本节点则跳过
            if(nodeList.item(i).getNodeType() == 3){
                continue;
            }
            //Node 节点
            Node stuNode = nodeList.item(i);
            //Element 元素 Node -> Element; 父类型 -> 子类型
            Element stuElement = (Element)stuNode;
            String name = stuElement.getAttribute("name");
            String age = stuElement.getAttribute("age");
            String gender = stuElement.getAttribute("gender");
            System.out.println(name + "\t" + age + "\t" + gender);

        }
    }
}
